package com.yanqu.road.utils.monitor;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.util.List;

public class FullGcMonitor implements Runnable {
    private static Logger gcLogger = LogManager.getLogger("fullGc");
    private long lastTimes;
    private long lastRecordTime;
    @Override
    public void run() {
        long curGcTimes = 0;
        List<GarbageCollectorMXBean> gcList = ManagementFactory.getGarbageCollectorMXBeans();
        for (GarbageCollectorMXBean gc : gcList) {
            String name = gc.getName();
            if (name.contains("MarkSweep")) {
                curGcTimes = gc.getCollectionCount();
            }
        }
        if (lastRecordTime != 0) {
            //1分钟计算一次
            long frequent = curGcTimes - lastTimes;
            if (frequent >= 3) {
                gcLogger.info("gc too frequent,times {}, totalTimes: {}", frequent, curGcTimes);
            } else {
                gcLogger.info("gc normal,times {}, totalTimes: {}", frequent, curGcTimes);
            }
        }
        lastTimes = curGcTimes;
        lastRecordTime = System.currentTimeMillis();
    }
}
